package com.gthncz.xxhelper.commons;

import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.CharBuffer;
import java.util.ArrayList;

/**
 * SQL 文件帮助类
 * Created by GT on 2019/11/10.
 */

public class SQLFileHelper {

    /**
     * 从文件中获取SQLs
     * @param pathName 文件路径文件名
     * @return SQLs
     * @throws IOException
     */
    public static ArrayList<String> getSqlsFromFile(String pathName)
            throws IOException {
        File file = new File(pathName);
        if (!file.exists()) throw new FileNotFoundException("文件不存在!");
        FileInputStream is = null;
        ArrayList<String> sqlList = null;
        try{
            is = new FileInputStream(file);
            sqlList = getSqlsFromStream(is);
        } finally {
            if (is != null) is.close();
        }
        return sqlList;
    }

    /**
     * 从 Assets 中获取 SQLs
     * @param context 上下文
     * @param assetName 资源文件名
     * @return SQLs
     * @throws IOException
     */
    public static ArrayList<String> getSqlsFromAssets(Context context, String assetName)
            throws IOException {
        ArrayList<String> sqlList = null;
        InputStream is = null;

        try{
            is = context.getResources().getAssets().open(assetName);
            sqlList = getSqlsFromStream(is);
        } finally {
            if (is != null) is.close();
        }
        return sqlList;
    }

    /**
     * 从输入流中获取 SQLs
     * @param is 输入流
     * @return SQLs
     * @throws IOException
     */
    public static ArrayList<String> getSqlsFromStream(InputStream is) throws IOException {
        ArrayList<String> sqlList = new ArrayList<>();
        // 1. 首先从输入流中获取SQLs
        StringBuffer buffer = new StringBuffer();
        InputStreamReader reader = null;
        try{
            reader = new InputStreamReader(is);
            char[] buf = new char[1024];
            int len = -1;
            while((len=reader.read(buf)) != -1){
                // 这里如果使用 BufferedReader 的 readline 方法读取，
                // 会使末尾缺少一个换行符，导致后面的正则匹配失败
                buffer.append(buf, 0, len);
            }
            String content = buffer.toString();
            // TODO 解决读取不全的问题
            Log.e("SQLFileHelper", content.substring(content.length()-10));
            // 2. 将每个SQL从content中解析出来
            String[] sqls = content.split(";[\r\n]+"); // 数据含有';', 导致出错
            // 3. 添加到集合中, 每行作为一个 SQL 语句
            for(String sql : sqls){
                sql = sql.trim();
                // 跳过注释 和 空(空语句引起错误)
                if (sql.equals("")) continue;
                if (sql.startsWith("--")) continue;
                if (sql.startsWith("#")) continue;
                // 添加SQL语句约束
                if (sql.startsWith("DROP")
                        || sql.startsWith("CREATE")
                        || sql.startsWith("INSERT")
                        || sql.startsWith("SELECT")
                        || sql.startsWith("UPDATE")
                        || sql.startsWith("DELETE"))
                {
                    sqlList.add(sql);
                }
            }
        } finally {
            if (reader != null) reader.close();
        }
        return sqlList;
    }

}
